<template>
    <div ref="privateChat" class="view-private-chat flex flex-direction-v">
        <mt-header class="chat-header" :title="toUser.toUserName">
            <mt-button @click="goBack" slot="left" icon="back"></mt-button>
            <mt-button @click="goBack" icon="" slot="right">
                <i class="iconfont icon-shanchu_"></i>
            </mt-button>
        </mt-header>
        <hr>
        <div ref="chartList" class="chat-list">
            <div v-for="item in messageList" :key="item.message" class="item">
                <div class="message-date">2018-05-17 12:47</div>
                <div v-if="item.fromUserId === userInfo.id" class="my-name flex">
                    <div v-if="item.message" class="content-box flex-1">
                        <span class="content">{{item.message}}</span>
                    </div>
                    <div v-else class="content-box img">
                        <div v-if="item.percent !== 100" class="mask"></div>
                        <button v-if="item.percent !== 100" type="button" class="percent">{{item.percent}}%</button>
                        <img class="messageImg" :src="item.imgUrl" />
                    </div>
                    <img class="userImg" :src="fromUser.headPortrait" />
                </div>
                <div v-else class="flex">
                    <img class="userImg" :src="fromUser.headPortrait" />
                    <div v-if="item.message" class="content-box flex-1">
                        <span class="content">{{item.message}}</span>
                    </div>
                    <div v-else class="content-box img">
                        <div v-if="item.percent !== 100" class="mask"></div>
                        <button v-if="item.percent === 100" type="button" class="percent" :class="{'active': item.percentFinish}">{{item.percent}}%</button>
                        <img class="messageImg" :src="item.imgUrl" />
                    </div>
                </div>
            </div>
        </div>
        <ali-oss-upload @uploadProgress="uploadProgress" @fileUploaded="imgUrlUploaded" :dirName="aliOss.dirName" :ossFile="aliOss.ossFile" :ossContainer="aliOss.ossContainer" :selectFiles="aliOss.selectFiles" :postFiles="aliOss.postFiles"></ali-oss-upload>
        <div class="chat-sendBox flex">
            <div :id="aliOss.ossContainer" class="sendImg-box flex flex-center-vh">
                <i ref="sendImg" id="pChat-avatar-uploader" class="iconfont icon-tupian sendImg"></i>
            </div>
            <div class="emoji-wrapper">
                <emoji-picker @emoji="append" :search="search">
                    <div
                        class="emoji-invoker"
                        slot="emoji-invoker"
                        slot-scope="{ events }"
                        v-on="events"
                    >
                        <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M0 0h24v24H0z" fill="none"/>
                        <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
                        </svg>
                    </div>
                    <div slot="emoji-picker" slot-scope="{ emojis, insert, display }">
                        <div class="emoji-picker" :style="{ top: display.y + 'px', left: display.x + 'px' }">
                            <div>
                                <div v-for="(emojiGroup, category) in emojis" :key="category">
                                    <h5>{{ category }}</h5>
                                    <div class="emojis">
                                        <span
                                        v-for="(emoji, emojiName) in emojiGroup"
                                        :key="emojiName"
                                        @click="insert(emoji)"
                                        :title="emojiName"
                                        >{{ emoji }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </emoji-picker>
            </div>
            <mt-field placeholder="你想说点什么..." v-model="newMessage">
                <mt-button @click="saveMessageData" class="sendPrivateMessage-btn" size="small">
                    <i class="iconfont icon-youjiantou"></i>
                </mt-button>
            </mt-field>
        </div>
    </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import util from "@/util/Util";
import dateFunc from "@/util/Date";
import _sessionUser from "@/util/SessionUser";
import _chatService from "@/service/chatService";
import AliOssUpload from "@/component/aliOssUpload/AliOssUpload";
import EmojiPicker from "vue-emoji-picker";

export default {
    name: "PrivateChat",
    data() {
        return {
            search: "",
            fromUser: {
                headPortrait: "./static/img/user/head-portrait.png"
            },
            toUser: {},
            messageList: [],
            newMessage: "",

            imgIsUploaded: false,
            imgUploadIndex: 0,
            aliOss: {
                ossFile: "pChat-ossFile",
                ossContainer: "pChat-ossContainer",
                selectFiles: "pChat-avatar-uploader",
                postFiles: "pChat-avatar-uploader",
                dirName:
                    "myVue-image" +
                    "/" +
                    dateFunc.dateFmt("yyyyMMdd", new Date()) +
                    "/"
            }
        };
    },
    mounted() {
        let vm = this;
        vm.toUser = vm.$route.query;
        _sessionUser.loadPage({
            scope: vm,
            exp: vm.userInfo,
            success: function() {
                vm.getMessageData();
                vm.$socket.on("receivePrivateMessage", data => {
                    vm.messageList.push(data);
                });
            }
        });
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.userInfo
        })
    },
    components: {
        "ali-oss-upload": AliOssUpload,
        EmojiPicker
    },
    directives: {
        focus: {
            inserted(el) {
                el.focus();
            }
        }
    },
    methods: {
        append(emoji) {
            this.newMessage += emoji;
        },
        goBack() {
            let vm = this;
            util.goBack(vm);
        },
        uploadProgress(percent) {
            let vm = this;
            let messageList = vm.messageList;
            let tempObj = {};
            let uploadIndex = 0;
            if (!vm.imgIsUploaded) {
                vm.messageList.push({
                    imgUrl: "",
                    percent: 0,
                    percentFinish: false
                });
            }
            uploadIndex = vm.messageList.length;
            vm.imgUploadIndex = uploadIndex;
            if (messageList && messageList.length > 0) {
                vm.messageList.forEach((v, i) => {
                    if (i === uploadIndex - 1) {
                        v.percent = percent;
                        tempObj = Object.assign({}, vm.messageList[i]);
                        vm.messageList.splice(i, 1, tempObj);
                    }
                });
            }
            vm.imgIsUploaded = true;
        },
        imgUrlUploaded(host, file) {
            let vm = this;
            let uploadIndex = 0;
            let messageList = vm.messageList;
            uploadIndex = vm.messageList.length;
            if (messageList && messageList.length > 0) {
                vm.messageList.forEach((v, i) => {
                    if (i === uploadIndex - 1) {
                        v.imgUrl = host + "/" + file;
                    }
                    setTimeout(() => {
                        v.percentFinish = true;
                    }, 500);
                });
            }
            vm.imgIsUploaded = false;
            vm.imgUploadIndex = uploadIndex;
            vm.percentFinish = true;
            // 聊天滚动条滑到最后
            vm.$refs.chartList.scrollTop = 100000;
        },
        // 发送用户私聊消息
        sendMessageBySocket() {
            let vm = this;
            let toUserId = vm.$route.query.toUserId * 1;
            vm.$socket.emit("sendPrivateMessage", {
                fromUserId: vm.userInfo.id,
                toUserId: toUserId,
                message: vm.newMessage
            });
            vm.newMessage = "";
        },
        // 获取用户历史私聊消息
        getMessageData() {
            let vm = this;
            let data;
            let resultData;
            let toUserId = vm.$route.query.toUserId * 1;
            let res = _chatService.getMessage({
                fromUser: vm.userInfo.id,
                toUser: toUserId,
                success: function(response) {
                    data = response.data.data;
                    resultData = response.data;
                    if (resultData.success) {
                        if (data && data.length > 0) {
                            data = data.reverse();
                            data.forEach(function(value, index) {
                                value.fromUserId = value.from_user;
                                vm.messageList.push(value);
                            });
                        }
                    } else {
                        vm.$toast({
                            message: resultData.message,
                            duration: 1000
                        });
                    }
                    console.log("获取用户历史私聊消息：" + resultData.message);
                }
            });
            return res;
        },
        // 保存用户私聊消息
        saveMessageData() {
            let vm = this;
            let resultData;
            let toUserId = vm.$route.query.toUserId * 1;

            if (!vm.newMessage) {
                vm.$toast({
                    message: "熊猫直播：内容不能为空",
                    position: "bottom",
                    duration: 1000
                });
                return;
            }

            let res = _chatService.sendMessage({
                fromUser: vm.userInfo.id,
                toUser: toUserId,
                message: vm.newMessage,
                success: function(response) {
                    resultData = response.data;
                    if (resultData.success) {
                        vm.sendMessageBySocket();
                    } else {
                        vm.$toast({
                            message: resultData.message,
                            duration: 1000
                        });
                    }
                    console.log("保存用户私聊消息：" + resultData.message);
                }
            });
            return res;
        }
    }
};
</script>

<style lang="scss" scoped>
.view-private-chat {
    background-color: #f5f5f5;
    height: 100%;
    overflow: hidden;
    .chat-header {
        background-color: #f7f7f7;
        color: #404040;
    }
    .chat-list {
        padding: 15px 0 70px;
        overflow-x: hidden;
        overflow-y: auto;
        .item {
            padding: 20px 15px 0;
        }
        .message-date {
            text-align: center;
            font-size: 10px;
            color: #b4b4b4;
            margin-bottom: 10px;
        }
        .userImg {
            width: 30px;
            height: 30px;
            object-fit: cover;
            border-radius: 50%;
        }
        .content-box {
            position: relative;
            margin: 0 40px 0 10px;
            overflow: hidden;
            &.img {
                width: 50vw;
                min-height: 50vw;
                .mask {
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.3);
                }
                .percent {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    margin-left: -25px;
                    margin-top: -25px;
                    text-align: center;
                    width: 50px;
                    height: 50px;
                    border: 1px solid rgba(0, 0, 0, 0.8);
                    color: rgba(0, 0, 0, 0.8);
                    font-size: 12px;
                    border-radius: 50%;
                    transform: scale(0.6);
                    z-index: 5;
                    transition: transform 0.5s ease-out;
                    &.active {
                        transform: matrix(12, 0, 0, 12, 0, 0);
                        border: none;
                        color: transparent;
                        background: rgba(0, 0, 0, 0.3);
                        animation: chatLoading 0.5s ease-in-out 0s 1 alternate
                            forwards;
                    }
                }
                .messageImg {
                    width: 100%;
                }
            }
        }
        .content {
            display: inline-block;
            padding: 7px;
            font-size: 13px;
            border-radius: 5px;
            background-color: #ffffff;
            color: #404040;
            /* 允许在单词内换行 */
            word-break: break-all;
        }
        .my-name {
            .content-box {
                margin: 0 10px 0 40px;
            }
            .content {
                float: right;
                background-color: #ff6e8b;
                color: white;
            }
        }
    }
    .chat-sendBox {
        position: fixed;
        bottom: 0;
        width: 100%;
        border-top: 1px solid #f2f2f2;
        color: #cecece;
        .mint-cell {
            background-color: #f8f8f8 !important;
        }
        .sendImg-box {
            position: absolute;
            top: 5px;
            left: -1px;
            width: 35px;
            height: 35px;
            z-index: 5;
            .sendImg {
                font-size: 24px;
                margin-left: 10px;
            }
        }
        .sendPrivateMessage-btn {
            background-color: white;
            border-top-right-radius: 20px;
            border-bottom-right-radius: 20px;
            border: 1px solid #f2f2f2;
            box-shadow: 0 0 1px #f2f2f2;
            .icon-youjiantou {
            }
        }
        .emoji-wrapper {
            position: relative;
            top: 3px;
            left: 35px;
            width: 35px;
            z-index: 1;
        }
    }
}
</style>

<style lang="scss">
.view-private-chat {
    .mint-cell {
        width: 100%;
    }
    .mint-field-core {
        position: relative;
        left: 30px;
        padding: 0 1px 0 15px;
        margin: 0 !important;
        line-height: 2;
        border: 1px solid #f2f2f2;
        border-top-left-radius: 20px;
        border-bottom-left-radius: 20px;
    }
    .emoji-invoker {
        position: relative;
        top: 0.5rem;
        left: 0.5rem;
        width: 1.5rem;
        height: 1.5rem;
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.2s;
        &:hover {
            transform: scale(1.1);
        }
        > svg {
            fill: #b1c6d0;
        }
    }
    .emoji-picker {
        position: absolute;
        left: -1rem !important;
        top: -10rem !important;
        z-index: 1;
        font-family: Montserrat;
        border: 1px solid #ccc;
        width: 15rem;
        height: 10rem;
        overflow: scroll;
        padding: 1rem;
        box-sizing: border-box;
        border-radius: 0.5rem;
        background: #fff;
        box-shadow: 1px 1px 8px #c7dbe6;
        h5 {
            margin-bottom: 0;
            color: #b1b1b1;
            text-transform: uppercase;
            font-size: 0.8rem;
            cursor: default;
        }
        .emojis {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            &:after {
                content: "";
                flex: auto;
            }
            span {
                padding: 0.2rem;
                cursor: pointer;
                border-radius: 5px;
                &:hover {
                    background: #ececec;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>